package com.my.config;



import com.my.model.Menu;
import com.my.model.Role;
import com.my.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;


/**
 * @功能
 * @创建时间 2020/3/8
 */
@Component
public class CustomMetadataSource implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    MenuService menuService;


    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        System.err.println(requestUrl);
        List<Menu> allMenus = menuService.getMenusWithRoles();
        for(Menu menu : allMenus){
            System.out.println(antPathMatcher.match(menu.getUrl(),requestUrl));
            if(antPathMatcher.match(menu.getUrl(),requestUrl)&&menu.getRoles().size()>0){ //遍历地址，能访问就跳转，不能就条登录
                List<Role> roles = menu.getRoles();
                String[] roleArr = new String[roles.size()];
                for(int i = 0;i < roleArr.length; i++){
                    roleArr[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);
            }
        }
        System.out.println("111");
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
